package com.chunxuan.langquan.ui.activity.live;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.chunxuan.langquan.R;
import com.chunxuan.langquan.ui.activity.store.adapter.BaseAdapter;
import com.chunxuan.langquan.ui.activity.store.adapter.BaseViewHolder;
import com.m7.imkfsdk.utils.ToastUtils;
import com.tencent.rtmp.ITXLivePlayListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXLivePlayConfig;
import com.tencent.rtmp.TXLivePlayer;
import com.tencent.rtmp.ui.TXCloudVideoView;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import static com.tencent.rtmp.TXLiveConstants.RENDER_MODE_ADJUST_RESOLUTION;
import static com.tencent.rtmp.TXLiveConstants.RENDER_MODE_FULL_FILL_SCREEN;

public class LiveRoomActivity extends AppCompatActivity {
    private TXLivePlayer mLivePlayer;               //直播拉流的视频播放器
    private TXCloudVideoView mVideoView;
    private ImageView mImageLoading;          //显示视频缓冲动画
    private boolean mIsPlaying = false;
    private TextView tvSpeed;
    public static void actionStart(Context context,String pullUrl) {
        Intent intent = new Intent(context, LiveRoomActivity.class);
        intent.putExtra("url",pullUrl);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_live_room);
        initialize();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroy();
    }

    private void initialize() {
        initPlayView();
        initPlayButton();
        initNavigationBack();
        // 初始化完成之后自动播放
        startPlay();
    }

    private void initPlayView() {
        mVideoView = (TXCloudVideoView) findViewById(R.id.video_view);
        mLivePlayer = new TXLivePlayer(this);
//        mLivePlayer.setRenderMode(RENDER_MODE_ADJUST_RESOLUTION);
        mLivePlayer.setRenderMode(RENDER_MODE_FULL_FILL_SCREEN);
        mImageLoading = (ImageView) findViewById(R.id.liveplayer_iv_loading);
        tvSpeed=findViewById(R.id.tv_speed_settings);
        tvSpeed.setVisibility(View.GONE);
    }

    private void initPlayButton() {

    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            destroy();
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
    private void togglePlay() {
        if (mIsPlaying) {
            stopPlay();
        } else {
            startPlay();
        }
    }

    private void initNavigationBack() {
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                destroy();
                finish();
            }
        });
    }


    public void startPlay() {
        startLoadingAnimation();
        mLivePlayer.setPlayerView(mVideoView);
        mLivePlayer.setPlayListener(new ITXLivePlayListener() {
            @Override
            public void onPlayEvent(int event, Bundle param) {
                Log.e("============", event + ":event");
                switch (event) {
                    case TXLiveConstants.PLAY_EVT_PLAY_BEGIN:

                    case TXLiveConstants.PLAY_EVT_RCV_FIRST_I_FRAME:
                        stopLoadingAnimation();
                        break;
                    case TXLiveConstants.PLAY_EVT_PLAY_LOADING:
                        startLoadingAnimation();
                        break;
                    case TXLiveConstants.PLAY_EVT_CHANGE_RESOLUTION:
                        break;
                    case TXLiveConstants.PLAY_EVT_GET_MESSAGE:
                        byte[] data = param.getByteArray(TXLiveConstants.EVT_GET_MSG);
                        String seiMessage = "";
                        if (data != null && data.length > 0) {
                            try {
                                seiMessage = new String(data, StandardCharsets.UTF_8);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        Toast.makeText(getApplicationContext(), seiMessage, Toast.LENGTH_SHORT).show();
                        break;
                    case TXLiveConstants.PLAY_EVT_CHANGE_ROTATION:
                        break;
                    case TXLiveConstants.PLAY_ERR_NET_DISCONNECT:
                    case TXLiveConstants.PLAY_EVT_PLAY_END:
                        stopPlay();
                        break;
                    default:
                        break;
                }
                if (event < 0) {
                    Toast.makeText(LiveRoomActivity.this,
                            param.getString(TXLiveConstants.EVT_DESCRIPTION), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onNetStatus(Bundle bundle) {

            }
        });


        //关键 player 对象与界面 view
        mLivePlayer.setPlayerView(mVideoView);
        int code = mLivePlayer.startPlay(getIntent().getStringExtra("url"), TXLivePlayer.PLAY_TYPE_LIVE_RTMP);
        mIsPlaying = code == 0;
        Log.e("code:", "code:" + code);
        //处理UI相关操作
        onPlayStart(code);
    }

    @Override
    public void onBackPressed() {
        stopPlay();
        super.onBackPressed();
    }

    private void stopPlay() {
        if (!mIsPlaying) {
            return;
        }
        if (mLivePlayer != null) {
            mLivePlayer.stopRecord();
            mLivePlayer.setPlayListener(null);
            mLivePlayer.stopPlay(true);
        }
        mIsPlaying = false;

        //处理UI相关操作
        onPlayStop();
    }

    public void onPlayStop() {
        stopLoadingAnimation();
    }

    public void onPlayStart(int code) {
        Log.e("设置背景", "onPlayStart");
        switch (code) {
            case Constants.PLAY_STATUS_SUCCESS:
                startLoadingAnimation();
                break;
            case Constants.PLAY_STATUS_INVALID_SECRET_RTMP_URL:
                new AlertDialog.Builder(this)
                        .setTitle("播放出错")
                        .setMessage("请检查地址")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Uri uri = Uri.parse(Constants.LIVE_PLAYER_REAL_TIME_PLAY_DOCUMENT_URL);
                        startActivity(new Intent(Intent.ACTION_VIEW, uri));
                        dialog.dismiss();
                    }
                }).show();
                break;
            default:
                break;
        }
        if (code != Constants.PLAY_STATUS_SUCCESS) {

            ToastUtils.showShort(this, "播放失败");
        } else {
            Log.e("设置背景", "====");

        }

    }

    private void startLoadingAnimation() {
        if (mImageLoading != null) {
            mImageLoading.setVisibility(View.VISIBLE);
            ((AnimationDrawable) mImageLoading.getDrawable()).start();
        }
    }

    private void stopLoadingAnimation() {
        if (mImageLoading != null) {
            mImageLoading.setVisibility(View.GONE);
            ((AnimationDrawable) mImageLoading.getDrawable()).stop();
        }
    }

    private void destroy() {
        if (mLivePlayer != null) {
            mLivePlayer.stopPlay(true);
            mLivePlayer = null;
        }
        if (mVideoView != null) {
            mVideoView.onDestroy();
            mVideoView = null;
        }
    }

}